package cn.skyquant.quant4j.service.boot.web.interceptor;


import cn.skyquant.quant4j.sdk.util.log.LogUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebLoggingInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        threadLocal.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Long begin = threadLocal.get();
        if(begin!=null){
            long diff = System.currentTimeMillis() - begin;
            LogUtil.info(LogUtil.web,String.format("%s, time=%dms",request.getRequestURI(),diff));
        }
    }
}
